//
//  PerfectCarInfoVC2.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/7/15.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "PerfectCarInfoVC2.h"
#import "TopBackView.h"
#import "CarView.h"
#import "PerfectCell.h"
#import "PerfectCarInfoVC3.h"
#import "QiniuSDK.h"
#import "Common.h"
#import "InstroctionViewController.h"
#import "ServeViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "WKProgressHUD.h"
#import "TimePickerView.h"
#import "LicenseVC.h"

#define spaceWidth 18 

@interface PerfectCarInfoVC2 ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSDictionary *dic;//分组字典

@property (nonatomic,strong) NSMutableDictionary *postDic;//上传字典
@property (nonatomic,strong) NSMutableDictionary *dataDic;//网络数据源
//@property (nonatomic,strong) NSMutableArray *buttonArr;//车辆结构数组
//@property (nonatomic,strong) NSMutableArray *cangButtonArr;//仓位数数组
//@property (nonatomic,strong) NSDictionary *carInfoDic;// 车辆信息

@property (nonatomic,strong) UITextField *licenseTextField;//驾驶证

@property (nonatomic,strong) NSIndexPath *indexPath;
@property (nonatomic,strong) UITextField *qianTextField;
@property (nonatomic,strong) UITextField *guaTextField;
@property (nonatomic) BOOL isAgree;
@property (nonatomic,strong) WKProgressHUD *hud;
@property (nonatomic,strong) UIView *backgroundView;
@property (nonatomic,strong) TimePickerView *timeView;
@property (nonatomic,strong) UIButton *timeButton;//选择时间
@property (nonatomic,strong) UIButton *licenseButton;//选择驾照类型



@end

@implementation PerfectCarInfoVC2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.postDic = [NSMutableDictionary dictionary];
//    self.buttonArr = [NSMutableArray array];
//    self.cangButtonArr = [NSMutableArray array];
    self.dataDic = [NSMutableDictionary dictionary];
    
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"司机认证"];
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:topBackView];
    
    self.view.backgroundColor = GrayColor;
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight)];
    self.scrollView.contentSize = CGSizeMake(screenWidth, screenHeight * 1.7);
    [self.view addSubview:self.scrollView];
    
    CarView *carView = [[CarView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 80) andInteger:2];
    carView.backgroundColor = WhiteColor;

    
    [self.scrollView addSubview:carView];
    
    self.dic = @{@"证件信息":@[@"营业执照照片",@"个人照片"],
                 @"车辆信息":@[@"牵引车正面照片",@"挂车尾照"]};
    
//    self.qianTextField = [[UITextField alloc]init];
//    self.qianTextField.placeholder = @"请输入牵引车车牌号";
//    self.qianTextField.returnKeyType = UIReturnKeyDone;
//    self.qianTextField.delegate = self;
    
//    self.guaTextField = [[UITextField alloc]init];
//    self.guaTextField.placeholder = @"请输入挂车车牌号";
//    self.guaTextField.delegate = self;
//    self.guaTextField.returnKeyType = UIReturnKeyDone;
    
//    self.licenseTextField = [[UITextField alloc]init];
//    self.licenseTextField.delegate = self;
//    self.licenseTextField.returnKeyType = UIReturnKeyDone;
//    self.licenseTextField.placeholder = @"请输入驾驶证类型";

    [self initSubView];

    [self initDataSource];
    
    self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

}

-(void)initDataSource
{
    
[Common requestWithUrlString:find_truckinfo contentType:application_json finished:^(id responseObj) {
    
    
    if ([[responseObj[@"data"] allKeys] count] == 0) {
        
        [self initSubView];
        [self.hud dismiss:YES];

    } else {
        
        self.dataDic = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
        
        [self initSubView];

        [self insertValueIntoDic];
        
        [self.hud dismiss:YES];
        
        [self.tableView reloadData];
    }
    
    
    
    
} failed:^(NSString *errorMsg) {
    
    [self.hud dismiss:YES];

    NSLog(@"%@",errorMsg);
}];
}
//赋值
-(void)insertValueIntoDic
{
    [self.postDic setObject:[self backString:self.dataDic[@"boxTypeCode"]] forKey:@"boxTypeCode"];
    [self.postDic setObject:[self backString:self.dataDic[@"boxTypeDesc"]]  forKey:@"boxTypeDesc"];
    [self.postDic setObject:[self backString:self.dataDic[@"jsMap"][@"key"]] forKey:@"jsKey"];
    [self.postDic setObject:[self backString:self.dataDic[@"xsMap"][@"key"]] forKey:@"xsKey"];
    //    [self.postDic setObject:[self backString:self.dataDic[@"dlMap"][@"key"]] forKey:@"dlKey"];
    [self.postDic setObject:[self backString:self.dataDic[@"qyMap"][@"key"]] forKey:@"qyKey"];
    [self.postDic setObject:[self backString:self.dataDic[@"gcMap"][@"key"]] forKey:@"gcKey"];
    [self.postDic setObject:[self backString:self.dataDic[@"tractorNumber"]] forKey:@"tractorNumber"];
    [self.postDic setObject:[self backString:self.dataDic[@"trailerNumber"]] forKey:@"trailerNumber"];
    [self.postDic setObject:[self backString:self.dataDic[@"storeNumberCode"]] forKey:@"storeNumberCode"];
    [self.postDic setObject:[self backString:self.dataDic[@"storeNumberDesc"]] forKey:@"storeNumberDesc"];
    [self.postDic setObject:[self backMoney:self.dataDic[@"id"]] forKey:@"id"];

}

-(void)initSubView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 90, screenWidth, 83 * 2 * kHeight + cellHeight * 2 + 10) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = GrayColor;
    [self.scrollView addSubview:self.tableView];
    
    [self.postDic setObject:@"" forKey:@"boxTypeCode"];
    [self.postDic setObject:@""  forKey:@"boxTypeDesc"];
    [self.postDic setObject:@"" forKey:@"jsKey"];
    [self.postDic setObject:@"" forKey:@"xsKey"];
    //    [self.postDic setObject:[self backString:self.dataDic[@"dlMap"][@"key"]] forKey:@"dlKey"];
    [self.postDic setObject:@"" forKey:@"qyKey"];
    [self.postDic setObject:@"" forKey:@"gcKey"];
    [self.postDic setObject:@"" forKey:@"tractorNumber"];
    [self.postDic setObject:@"" forKey:@"trailerNumber"];
    [self.postDic setObject:@"" forKey:@"storeNumberCode"];
    [self.postDic setObject:@"" forKey:@"storeNumberDesc"];
    [self.postDic setObject:@"" forKey:@"id"];

    [self initBottomView];
}



-(void)initBottomView
{

    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(14, CGRectGetMaxY(self.tableView.frame) + 20, screenWidth - 28, Button_height);
    nextButton.backgroundColor = YellowColor;
    [nextButton setTitle:@"提交信息" forState:UIControlStateNormal];
    [nextButton setTitleColor:WhiteColor forState:UIControlStateNormal];
    nextButton.layer.cornerRadius = 5;
    [nextButton addTarget:self action:@selector(nextButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.scrollView addSubview:nextButton];
    
    
    if ([ self.dataDic[@"status"]  isKindOfClass:[NSNull class]]) {
        
        
    } else {
        
        if ([self.dataDic[@"status"] integerValue] == 10 || [self.dataDic[@"status"] integerValue] == 30 ) {
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(0, 0, screenWidth, CGRectGetMinY(nextButton.frame));
            
            [self.scrollView addSubview:button];
            [button addTarget:self action:@selector(tishiMessage) forControlEvents:UIControlEventTouchUpInside];
            
            nextButton.backgroundColor = Color_RGB(154, 154, 154, 1);
            nextButton.userInteractionEnabled = NO;
            
            }
 
    }
    
    self.scrollView.contentSize = CGSizeMake(screenWidth, CGRectGetMaxY(nextButton.frame) + 20 + 64);
}

-(void)tishiMessage
{
    [WKProgressHUD popMessage:@"认证中和认证通过信息不能修改" inView:self.view duration:1.5 animated:YES];

}


-(UIButton *)backButtonWithString:(NSString *)title andFont:(NSInteger)integer andFrame:(CGRect)frame
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:YellowColor forState:UIControlStateNormal];
    button.titleLabel.font = Font(integer);
    
    return button;
}

#pragma mark button 方法
//以阅读
-(void)agreeButton
{
    UIImageView *img = (UIImageView *)[self.view viewWithTag:600];
    
    if (_isAgree) {
        img.image = [UIImage imageNamed:@"regist_unselected"];
        _isAgree = NO;
    } else {
        img.image = [UIImage imageNamed:@"regist_selected"];

        _isAgree = YES;
    }


}
//运输说明按钮

-(void)transButton{
    //运输说明
    InstroctionViewController *instroctionVC = [[InstroctionViewController alloc]init];
    [self.navigationController pushViewController:instroctionVC animated:YES];

}

//车辆运输服务协议

-(void)backButton
{
    //服务
    ServeViewController *serveVC = [[ServeViewController alloc]init];
    
    [self.navigationController pushViewController:serveVC animated:YES];
}

-(void)nextButton
{
    
    
//    if (_isAgree) {
    
        NSString *str = [NSString stringWithFormat:@"%@",self.dataDic[@"id"]];
        
        if (self.dataDic[@"id"] == nil) {
            
            [self.postDic removeObjectForKey:@"id"];
            
        } else {
            
            [self.postDic setObject:@([str integerValue]) forKey:@"id"];
        }

        NSArray *arr = [self.postDic allValues];
    
        for (int i = 0; i < arr.count; i++) {
            
            if ([[NSString stringWithFormat:@"%@",arr[i]] isEqualToString:@""]) {
               
                [WKProgressHUD popMessage:@"请将信息补充完毕" inView:self.view duration:1.5 animated:YES];
                
                return;
                
            }
        }
        
        
    Common *c = [[Common alloc]init];
    [c afPostRequestWithUrlString:truckinfo_save parms:self.postDic finishedBlock:^(id responseObj) {
        
         NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
         [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
        
        if ([dic[@"success"] boolValue]) {
            
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                PerfectCarInfoVC3 *perfect3 = [[PerfectCarInfoVC3 alloc]init];
                
                [self.navigationController pushViewController:perfect3 animated:YES];
            });
            
           
        }
        
       
        
    } failedBlock:^(NSString *errorMsg) {
        
        
        
        NSLog(@"%@",errorMsg);
    }];
        

}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//    NSArray *arr = [self.dic allKeys];
//    return arr.count;
//    return 2;
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
//    NSArray *arr = [self.dic allKeys];
//    
//    return [self.dic[arr[section]] count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = @"PerfectCell";
    PerfectCell *cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"PerfectCell" owner:nil options:nil] firstObject];
    }
    
    
    NSArray *arr = [self.dic allKeys];
    NSString *valueS = self.dic[arr[indexPath.section]][indexPath.row];
    cell.titleL.text = [NSString stringWithFormat:@"%@",valueS];
    
    if (indexPath.row == 0) {
        cell.detailTileL.text = @"(需完整清晰无遮挡)";
    } else {
        cell.detailTileL.text = @"(上传正面半身照片)";

    }
    
    
    if ([[self.dataDic allKeys] count ] > 0) {
    
    //驾驶证照片
    if ([[self.dataDic[@"jsMap"] allKeys] count] > 0) {
        if (indexPath.section == 0 && indexPath.row == 0) {
            NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDic[@"jsMap"][@"url"]]];
            
//            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"]];
            
            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (error != nil) {
                    
                    cell.touchImageV.image = [UIImage imageNamed:@"bad_picture"];
                }
                
                
            }];
            
        }
    }
    
    //行驶证照片
    if ([[self.dataDic[@"xsMap"] allKeys] count] > 0) {
        if (indexPath.section == 0 && indexPath.row == 1) {
            NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDic[@"xsMap"][@"url"]]];
            
//            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"]];
            
            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (error != nil) {
                    
                    cell.touchImageV.image = [UIImage imageNamed:@"bad_picture"];
                }
                
                
            }];
            
        }
    }

//    //道路运输证照片
//    if ([[self.dataDic[@"dlMap"] allKeys] count] > 0) {
//        if (indexPath.section == 0 && indexPath.row == 2) {
//            NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDic[@"dlMap"][@"url"]]];
//            
//            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"]];
//            
//        }
//    }

    /*
        
    //牵引车正面照片
    if ([[self.dataDic[@"qyMap"] allKeys] count] > 0) {
        if (indexPath.section == 1 && indexPath.row == 0) {
            NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDic[@"qyMap"][@"url"]]];
            
//            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"]];
            
            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (error != nil) {
                    
                    cell.touchImageV.image = [UIImage imageNamed:@"bad_picture"];
                }
                
            }];
            
        }
    }

    //挂车尾照
    if ([[self.dataDic[@"gcMap"] allKeys] count] > 0) {
        if (indexPath.section == 1 && indexPath.row == 1) {
            NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.dataDic[@"gcMap"][@"url"]]];
            
//            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"]];
            
            [cell.touchImageV sd_setImageWithURL:urls placeholderImage:[UIImage imageNamed:@"car_add"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                
                if (error != nil) {
                    
                    cell.touchImageV.image = [UIImage imageNamed:@"bad_picture"];
                }
                
                
            }];
            
        }
    }
     */


    }
     
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, cellHeight * 2 )];
    
//    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 200, cellHeight)];
//    label.textColor = littleBlackColor;
//    label.font = Font(14);
//    label.text = arr[section];
//    [view addSubview:label];
//    view.backgroundColor = WhiteColor;
    
    
    UIView *firstV = [self backViewWithString:@"驾驶证类型" andTextField:self.licenseTextField andFolat:0];
    [view addSubview:firstV];
    
    self.licenseButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.licenseButton.frame = CGRectMake(screenWidth - 200 - 15, 0, 200, cellHeight);
    self.licenseButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.licenseButton.titleLabel.font = Font(13);
    [self.licenseButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    [self.licenseButton addTarget:self action:@selector(choiceLicense) forControlEvents:UIControlEventTouchUpInside];
    
    //初始化button显示时间
    
    [self.licenseButton setTitle:@"A1" forState:UIControlStateNormal] ;
    [firstV addSubview:self.licenseButton];
    
    view.backgroundColor = WhiteColor;

    
    
    UIView *secondV = [self backViewWithString:@"领证时间" andTextField:self.guaTextField andFolat:cellHeight ];
    [view addSubview:secondV];
    
   self.timeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.timeButton.frame = CGRectMake(screenWidth - 200 - 15, 0, 200, cellHeight);
    self.timeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.timeButton.titleLabel.font = Font(13);
    [self.timeButton setTitleColor:littleBlackColor forState:UIControlStateNormal];
    
    [self.timeButton addTarget:self action:@selector(choiceDate) forControlEvents:UIControlEventTouchUpInside];
    
    //初始化button显示时间
    NSDateFormatter *forma = [[NSDateFormatter alloc]init];
    
    [forma setDateFormat:@"YYYY年-MM月-dd日"];
    [self.timeButton setTitle:[forma stringFromDate: [NSDate date]] forState:UIControlStateNormal] ;
    [secondV addSubview:self.timeButton];
    
    return view;

    
  }

#pragma mark 选择时间
-(void)choiceDate
{
    
    __weak typeof(self) weakSelf = self;
    
    self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    
    self.timeView = [[TimePickerView alloc]initWithFrame:CGRectMake(0, screenHeight, screenWidth, screenHeight)];
    self.timeView.datePicker.maximumDate = [NSDate date];
    

    NSString* string = @"1955-01-01";
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    self.timeView.datePicker.minimumDate = inputDate;

    
    self.timeView.backgroundColor = WhiteColor;
    self.timeView.callBack = ^(NSString *str){
        
        if (str == nil) {
            
        } else {
            [weakSelf.timeButton setTitle:str forState:UIControlStateNormal];
        }
        
        
        [UIView animateWithDuration:0.4 animations:^{
            
            [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
            
            weakSelf.timeView.frame = CGRectMake(0, screenHeight  , screenWidth, 200);
            
        } completion:^(BOOL finished) {
            [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:1]];
            
            [weakSelf.backgroundView removeFromSuperview];
        }];
    };
    
    
    
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
    
    [UIView animateWithDuration:0.4 animations:^{
        
        [weakSelf.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        
        weakSelf.timeView.frame = CGRectMake(0, screenHeight - 200, screenWidth, 200);
        
        [window addSubview:weakSelf.backgroundView];
        [weakSelf.backgroundView addSubview:weakSelf.timeView];
        
        
        
    } completion:^(BOOL finished) {
        //        [self.backgroundView setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
        
    }];
    
}

-(void)choiceLicense
{
    LicenseVC *licenseVC = [[LicenseVC alloc]init];
    
    [self.navigationController pushViewController:licenseVC animated:YES];
}



-(NSString *)backString:(NSString *)string
{
    
    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}

-(NSString *)backMoney:(NSString *)string
{
    NSString   *str = [NSString stringWithFormat:@"%@",string];
    
    if ([str isEqual:[NSNull null]]) {
        return @"";
    } else {
        return [NSString stringWithFormat:@"%@",str];
    }
    
    
}


-(UIView *)backViewWithString:(NSString *)str andTextField:(UITextField *)textF andFolat:(CGFloat)y
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, y, screenWidth, cellHeight)];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 0.5)];
    label.backgroundColor = LineGrayColor;
    [view addSubview:label];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(18, 0, 100, cellHeight)];
    label1.text = str;
    label1.textColor = fontGrayColor;
    label1.font = Font(12);
    [view addSubview:label1];
    
    textF.frame = CGRectMake(screenWidth - 15 - 200, 0, 200, cellHeight);
    textF.textColor = littleBlackColor;
    textF.font = Font(12);
    textF.textAlignment = NSTextAlignmentRight;
    [view addSubview:textF];
    
    return view;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.indexPath = indexPath;
    [self tapSelectPicture];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 83 * kHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return section == 0 ? cellHeight * 2 :cellHeight * 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
}



//获取图片
-(void)tapSelectPicture
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf getPictureFromCamera];
        
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf getPictureFromLibrary];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [self presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [self presentViewController:picker animated:YES completion:nil];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//
        PerfectCell *cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
        cell.touchImageV.image = image;
        
        self.hud = [WKProgressHUD showInView:self.view withText:@"" animated:YES];

        
        //上传服务器
        [self getTokenFromQN];
        
    }];
}


-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.3);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    //    NSString *string = [NSString stringWithFormat:@"%@qiniu/upload/ticket",Main_interface];
    
    [Common requestWithUrlString:qiniu_token contentType:application_json finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            PerfectCell *cell = [self.tableView cellForRowAtIndexPath:self.indexPath];
            [self uploadImageToQNWithData:[self getImageWith:cell.touchImageV.image] andToken:responseObj[@"data"]];
            
        }
    } failed:^(NSString *errorMsg) {
        
        [self.hud dismiss:YES];
        
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data andToken:(NSString *)string
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:string complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        

        
        if (self.indexPath.section == 0 && self.indexPath.row == 0) {
            [self.postDic setObject:resp[@"key"] forKey:@"jsKey"];

        }
        
        if (self.indexPath.section == 0 && self.indexPath.row == 1) {
            [self.postDic setObject:resp[@"key"] forKey:@"xsKey"];
            
        }
        
//        if (self.indexPath.section == 0 && self.indexPath.row == 2) {
//            [self.postDic setObject:resp[@"key"] forKey:@"dlKey"];
//            
//        }
        
        if (self.indexPath.section == 1 && self.indexPath.row == 0) {
            [self.postDic setObject:resp[@"key"] forKey:@"qyKey"];
            
        }
        
        if (self.indexPath.section == 1 && self.indexPath.row == 1) {
            [self.postDic setObject:resp[@"key"] forKey:@"gcKey"];
            
        }
        
        [self.hud dismiss:YES];
        
    } option:uploadOption];
}



-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
